﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using XiAnAirport.BUS;
using XiAnAirport.DAL;
using XiAnAirport.Job;
using XiAnAirport.Models;

namespace XiAnAirport
{
    public class WorkService
    {
        public static void UpdateArea()
        {
            try
            {
                ElevatorAreaDAL elevatorAreaDAL = new ElevatorAreaDAL();
                elevatorAreaDAL.TruncateArea();
                ElevatorAreaBUS bUS = new ElevatorAreaBUS();
                List<AreaInfo> list = bUS.GetAllArea();
                foreach (var item in list)
                {
                    try
                    {
                        AreaInfo areaInfo = new AreaInfo();
                        areaInfo.id = item.id;
                        areaInfo.areaName = item.areaName;
                        areaInfo.mainAreaId = item.mainAreaId;
                        areaInfo.isDelete = 0;
                        bool result = elevatorAreaDAL.CheckArea(item.id);
                        if (result)
                        {
                            elevatorAreaDAL.EditArea(areaInfo);
                        }
                        else
                        {
                            elevatorAreaDAL.AddArea(areaInfo);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {

            }
        }

        public static void Init()
        {
            InitDeviceList();//初始化设备列表
            //InitDeviceRun();//初始化设备运行情况
            InitDevice();//初始化设备数量
            OrderIncomplete();//初始化未完成工单数量
            InitWorkOrder();//初始化日常工作
            InitFault();//初始化故障数量

        }
        public static void InitDeviceRun()
        {
            try
            {
                ElevatorAreaDAL da = new ElevatorAreaDAL();
                string dt = DateTime.Now.ToString("yyyy-MM-dd");
                //List<ElevatorStateRunTime> elevatorStateRunTimes = da.QueryRunTimeToday(dt);
                //List<ElevatorStateRun> elevatorStateRun = da.QueryRunsToday(dt);
                //ElevatorStateBUS.runtime_list = elevatorStateRunTimes;
                //ElevatorStateBUS.run_list = elevatorStateRun;
            }
            catch
            {

            }
        }

        public static void InitDeviceList()
        {
            try
            {
                ElevatorAreaDAL da = new ElevatorAreaDAL();
                Elevator elevator = new Elevator();
                List<Elevator> elevators = da.QueryElevator(elevator);
                List<ElevatorRunInfo> runs_list = da.QueryElevatorRunsTotal();
                List<ElevatorRunInfo> time_list = da.QueryElevatorRunTimeTotal();
                List<LiftStateALL> states = new List<LiftStateALL>();
                if (elevators != null && elevators.Count > 0)
                {
                    for (int i = 0; i < elevators.Count; i++)
                    {
                        LiftStateALL liftState = new LiftStateALL();
                        Elevator elevator1 = elevators[i];
                        int run_id = runs_list.FindIndex(x => x.elevatorId == elevator1.id);
                        if (run_id > -1)
                        {
                            elevator1.Runs = runs_list[run_id].runsTotal;
                        }
                        int time_id = time_list.FindIndex(x => x.elevatorId == elevator1.id);
                        if (time_id > -1)
                        {
                            elevator1.RunTimeSecond = time_list[time_id].runTimeTotal;
                        }
                        elevator1.lastmaintenanceTime = da.QuerylastMaintenance(elevators[i].id);
                        elevator1.maintenanceTime = da.QuerylastRepairTime(elevators[i].id);
                        elevator1.nextmaintenanceTime = da.QueryNextMaintenance(elevators[i].id);
                        elevator1.faultnum = da.QueryElevatorFault(elevators[i].id);
                        elevators[i] = elevator1;
                    }
                }
                ElevatorStateBUS.device_list = elevators;
                KoneDeviceStatus koneDeviceStatus = new KoneDeviceStatus();
                koneDeviceStatus.offlineTotal = elevators.Count;
                koneDeviceStatus.deviceTotal = elevators.Count;
                ElevatorStateBUS.KoneDeviceStatus = koneDeviceStatus;
                //InitMaintime(elevators);
            }
            catch
            {

            }
        }

        public static void OrderIncomplete()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                for (int i = 0; i < 4; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;
                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "fault";
                            //datanum = mqttDataDAL.QueryUntreatedFault();
                            datanum = 0;
                        }
                        else if (i == 1)
                        {
                            type = "inspection";
                            datanum = mqttDataDAL.QueryUntreatedInspectionOrder();
                        }
                        else if (i == 2)
                        {
                            type = "repair";
                            datanum = mqttDataDAL.QueryUntreatedRepairOrder();
                        }
                        else if (i == 3)
                        {
                            type = "maintain";
                            datanum = mqttDataDAL.QueryUntreatedMaintainOrder();
                        }
                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "OrderIncomplete";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {

                    }
                }
            }
            catch
            {

            }
        }

        public static void InitDevice()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                mqttDataDAL.ClearKoneDeviceTotal();
                int devicetotal = mqttDataDAL.QueryDeviceTotal();
                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;
                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "normalTotal";
                            datanum = 0;
                        }
                        else if (i == 1)
                        {
                            type = "faultTotal";
                            datanum = 0;
                        }
                        else if (i == 2)
                        {
                            type = "maintenanceTotal";
                            datanum = 0;
                        }
                        else if (i == 3)
                        {
                            type = "offlineTotal";
                            datanum = devicetotal;
                        }
                        else if (i == 4)
                        {
                            type = "deviceTotal";
                            datanum = devicetotal;
                        }
                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "DeviceStatusTotal";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }

                //初始化迅达、东芝、TKE设备数量
                for (int k = 0; k < 3; k++)
                {
                    string topicType = string.Empty;
                    string manufacturer = string.Empty;
                    string manufacturerId = string.Empty;
                    string type = string.Empty;
                    if (k == 0)
                    {
                        topicType = "DeviceStatusTotal";
                        manufacturer = "Schindler";
                        manufacturerId = "01";
                        type = "deviceTotal";
                        InitDeviceNum(manufacturer, manufacturerId, type, topicType);
                    }
                    else if (k == 1)
                    {
                        topicType = "DeviceStatusTotal";
                        manufacturer = "TKE";
                        manufacturerId = "02";
                        type = "deviceTotal";
                        InitDeviceNum(manufacturer, manufacturerId, type, topicType);
                    }
                    else if (k == 2)
                    {
                        topicType = "DeviceStatusTotal";
                        manufacturer = "TOSHIBA";
                        manufacturerId = "03";
                        type = "deviceTotal";
                        InitDeviceNum(manufacturer, manufacturerId, type, topicType);
                    }
                }
            }
            catch
            {

            }
        }

        public static void InitDeviceNum(string manufacturer, string manufacturerId, string type, string topicType)
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                bool result = mqttDataDAL.CheckData(manufacturer, manufacturerId, type, topicType);
                if (!result)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        mqttdata mqttdata = new mqttdata();
                        mqttdata.dataNum = 0;
                        mqttdata.topicType = topicType;
                        mqttdata.manufacturer = manufacturer;
                        mqttdata.manufacturerId = manufacturerId;
                        if (i == 0)
                        {
                            mqttdata.dataType = "normalTotal";
                        }
                        else if (i == 1)
                        {
                            mqttdata.dataType = "faultTotal";
                        }
                        else if (i == 2)
                        {
                            mqttdata.dataType = "maintenanceTotal";
                        }
                        else if (i == 3)
                        {
                            mqttdata.dataType = "offlineTotal";
                        }
                        else if (i == 4)
                        {
                            mqttdata.dataType = "deviceTotal";
                        }
                        mqttDataDAL.AddMqttData(mqttdata);
                    }
                }
            }
            catch
            {

            }
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int inspection = 0;
                int maintenance = 0;
                int fault = 0;
                int old_value = 0;
                List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                for (int i = 0; i < 6; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "inspectionTotal";
                            old_value = (int)list.FirstOrDefault(x => x.dataType == "inspection").dataNum;
                            datanum = old_value + mqttDataDAL.QueryInspectionOrder();
                            inspection = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "maintenanceTotal";
                            old_value = (int)list.FirstOrDefault(x => x.dataType == "maintain").dataNum;
                            datanum = old_value + mqttDataDAL.QueryMaintainOrder() ;
                            maintenance = datanum;
                        }
                        else if (i == 2)
                        {
                            type = "faultTotal";
                            old_value = (int)list.FirstOrDefault(x => x.dataType == "repair").dataNum;
                            //old_value = list.FirstOrDefault(x => x.dataType == "fault").dataNum;
                            datanum = old_value + mqttDataDAL.QueryRepairOrder();
                            fault = datanum;
                        }
                        else if (i == 3)
                        {
                            type = "inspectionCompleted";
                            datanum = inspection - mqttDataDAL.QueryInCompleteInspectionOrder();
                        }
                        else if (i == 4)
                        {
                            type = "maintenanceCompleted";
                            datanum = maintenance - mqttDataDAL.QueryInCompleteMaintainOrder();
                        }
                        else if (i == 5)
                        {
                            type = "faultCompleted";
                            //datanum = fault - mqttDataDAL.QueryInCompletelFault();
                            datanum = fault - mqttDataDAL.QueryInCompletelRepairOrder();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {

            }
        }

        public static void InitFault()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;
                        mqttdata mqttdata = new mqttdata();

                        if (i == 0)
                        {
                            type = "faultTotal";
                            datanum = mqttDataDAL.QueryTotalFault();
                        }
                        else if (i == 1)
                        {
                            type = "faultToday";
                            datanum = mqttDataDAL.QueryTodayFault();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "FaultStatistics";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch
            {

            }
        }

        public static async void Work()
        {
            //调度器工厂
            ISchedulerFactory Work = new StdSchedulerFactory();
            //调度器
            IScheduler schedulers_work = await Work.GetScheduler();
            await schedulers_work.GetJobGroupNames();
            /*-------------计划任务代码实现------------------*/
            //创建任务
            IJobDetail job_Work = JobBuilder.Create<ElevatorScheduled>()
                .WithIdentity("TimeTrigger", "TimeGroup")
                .Build();
            //创建触发器 2点一分时被执行
            //ITrigger trigger9 = TriggerBuilder.Create().WithCronSchedule("0 01 02 * * ?").WithIdentity("TimeTriggerddd", "TimeGroupdd").Build();
            //每隔多久执行一次  这个是每隔多久执行一遍
            //int sj = Convert.ToInt32(CommVars.Configuration.GetSection("QueryInterval").Value);
            int sj = Convert.ToInt32(AppSettingsHelper.Configuration["QueryInterval"]);
            ElevatorStateBUS.Offline = Convert.ToInt32(AppSettingsHelper.Configuration["OfflineTime"]);
            LogHelper.Log("定时查询时间" + sj + ",超时时间" + ElevatorStateBUS.Offline);
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("TimeTrigger", "TimeGroup").WithSimpleSchedule(t => t.WithIntervalInSeconds(sj).RepeatForever()).Build();//间隔执行一次任务
            //添加任务及触发器至调度器中
            await schedulers_work.ScheduleJob(job_Work, trigger);
            /*-------------计划任务代码实现------------------*/
            //启动
            await schedulers_work.Start();
        }

        public static async void WorkOrder()
        {
            try
            {
                //调度器工厂
                ISchedulerFactory Work = new StdSchedulerFactory();
                //调度器
                IScheduler schedulers_work = await Work.GetScheduler();
                await schedulers_work.GetJobGroupNames();
                /*-------------计划任务代码实现------------------*/
                //创建任务
                IJobDetail job_Work = JobBuilder.Create<WorkOrderJob>()
                    .WithIdentity("TimeTrigger1", "TimeGroup1")
                    .Build();
                //创建触发器 0点0分时被执行
                //每隔多久执行一次  这个是每隔多久执行一遍
                ITrigger trigger = TriggerBuilder.Create().WithCronSchedule("0 0 0 * * ?").WithIdentity("TimeTrigger1", "TimeGroup1").Build();//间隔执行一次任务
                                                                                                                                              //添加任务及触发器至调度器中
                await schedulers_work.ScheduleJob(job_Work, trigger);
                /*-------------计划任务代码实现------------------*/
                //启动
                await schedulers_work.Start();
            }
            catch
            {

            }
        }

        public static async void Operation()
        {
            try
            {
                //调度器工厂
                ISchedulerFactory Work = new StdSchedulerFactory();
                //调度器
                IScheduler schedulers_work = await Work.GetScheduler();
                await schedulers_work.GetJobGroupNames();
                /*-------------计划任务代码实现------------------*/
                //创建任务
                IJobDetail job_Work = JobBuilder.Create<OperationJob>()
                    .WithIdentity("TimeTrigger2", "TimeGroup2")
                    .Build();
                //创建触发器 2点一分时被执行
                //每隔多久执行一次  这个是每隔多久执行一遍
                ITrigger trigger = TriggerBuilder.Create().WithIdentity("TimeTrigger2", "TimeGroup2").WithSimpleSchedule(t => t.WithIntervalInSeconds(1800).RepeatForever()).Build();//间隔半小时执行一次任务
                                                                                                                                                                                     //添加任务及触发器至调度器中
                await schedulers_work.ScheduleJob(job_Work, trigger);
                /*-------------计划任务代码实现------------------*/
                //启动
                await schedulers_work.Start();
            }
            catch
            {

            }
        }

        public static async void DataPush()
        {
            //调度器工厂
            ISchedulerFactory Work = new StdSchedulerFactory();
            //调度器
            IScheduler schedulers_work = await Work.GetScheduler();
            await schedulers_work.GetJobGroupNames();
            /*-------------计划任务代码实现------------------*/
            //创建任务
            IJobDetail job_Work = JobBuilder.Create<DataPushJob>()
                .WithIdentity("TimeTrigger3", "TimeGroup3")
                .Build();
            //创建触发器 2点一分时被执行
            //每隔多久执行一次  这个是每隔多久执行一遍
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("TimeTrigger3", "TimeGroup3").WithSimpleSchedule(t => t.WithIntervalInMinutes(5).RepeatForever()).Build();//间隔5分钟执行一次任务
            //添加任务及触发器至调度器中
            await schedulers_work.ScheduleJob(job_Work, trigger);
            /*-------------计划任务代码实现------------------*/
            //启动
            await schedulers_work.Start();
        }

        public static async void ClearLog()
        {
            try
            {
                //调度器工厂
                ISchedulerFactory Work = new StdSchedulerFactory();
                //调度器
                IScheduler schedulers_work = await Work.GetScheduler();
                await schedulers_work.GetJobGroupNames();
                /*-------------计划任务代码实现------------------*/
                //创建任务
                IJobDetail job_Work = JobBuilder.Create<ClearLogJob>()
                    .WithIdentity("ClearLog_TimeTrigger3", "ClearLog_TimeGroup3")
                    .Build();
                //创建触发器 2点一分时被执行
                //每隔多久执行一次  这个是每隔多久执行一遍
                ITrigger trigger = TriggerBuilder.Create().WithIdentity("ClearLog_TimeTrigger3", "ClearLog_TimeGroup3").WithSimpleSchedule(t => t.WithIntervalInHours(24).RepeatForever()).Build();//间隔5分钟执行一次任务
                                                                                                                                                                                                   //添加任务及触发器至调度器中
                await schedulers_work.ScheduleJob(job_Work, trigger);
                /*-------------计划任务代码实现------------------*/
                //启动
                await schedulers_work.Start();
            }
            catch
            {

            }
        }

        public static async void UpdateRuns()
        {
            try
            {
                //调度器工厂
                ISchedulerFactory Work = new StdSchedulerFactory();
                //调度器
                IScheduler schedulers_work = await Work.GetScheduler();
                await schedulers_work.GetJobGroupNames();
                /*-------------计划任务代码实现------------------*/
                //创建任务
                IJobDetail job_Work = JobBuilder.Create<RunJob>()
                    .WithIdentity("TimeTrigger_RunJob", "TimeGroup_RunJob")
                    .Build();
                //创建触发器 2点一分时被执行
                //每隔多久执行一次  这个是每隔多久执行一遍
                ITrigger trigger = TriggerBuilder.Create().WithIdentity("TimeTrigger_RunJob", "TimeGroup_RunJob").WithSimpleSchedule(t => t.WithIntervalInMinutes(10).RepeatForever()).Build();//间隔10分钟
                                                                                                                                                                                               //添加任务及触发器至调度器中
                await schedulers_work.ScheduleJob(job_Work, trigger);
                /*-------------计划任务代码实现------------------*/
                //启动
                await schedulers_work.Start();
            }
            catch
            {

            }
        }
    }
}
